package com.meixiang.activity.account.myAppointment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.myShopper.OrderRefundActivity;
import com.meixiang.activity.homes.cosmeticTraining.CosmeticTrainingDetailActivity;
import com.meixiang.activity.homes.service.BeautyClinicDetailActivity;
import com.meixiang.activity.homes.service.CosmetologistActivity;
import com.meixiang.activity.homes.service.ReservationActivity;
import com.meixiang.activity.homes.service.ServiceDetailActivity;
import com.meixiang.activity.homes.shopping.CashierDeskActivity;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.servicOrder.ServiceOrderDetial;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.CircleImageView;
import com.meixiang.view.StarLayout;
import com.meixiang.view.TitleView;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 预约详情
 * @author xyj
 */
public class AppointmentDetailActivity extends BaseActivity {
    @Bind(R.id.title)
    TitleView titleView; //头部视图
    @Bind(R.id.appointment_detail_tv_order_name)
    TextView appointment_detail_tv_order_name; //服务名称
    @Bind(R.id.appointment_detail_tv_order_state)
    TextView appointment_detail_tv_order_state; //预约状态
    @Bind(R.id.all_order_item_iv)
    ImageView all_order_item_iv;
    @Bind(R.id.all_order_item_tv_detail)
    TextView all_order_item_tv_detail;
    @Bind(R.id.all_order_item_tv_price)
    TextView all_order_item_tv_price;
    @Bind(R.id.all_order_item_tv_amount)
    TextView all_order_item_tv_amount;
    @Bind(R.id.rl_goods_info_layout)
    RelativeLayout rl_goods_info_layout; //商品信息栏
    @Bind(R.id.appointment_refund_detali_rl)
    RelativeLayout appointment_refund_detali_rl; //查看退款详情
    @Bind(R.id.rl_technician_detail)
    RelativeLayout rl_technician_detail; //美容师
    @Bind(R.id.iv_portrait)
    CircleImageView iv_portrait;  //头像
    @Bind(R.id.tv_technician_name)
    TextView tv_technician_name; // 名字
    @Bind(R.id.tv_appointment_serve_time)
    TextView tv_appointment_serve_time; //服务时间
    @Bind(R.id.ll_address_serve)
    LinearLayout ll_address_serve ;
    @Bind(R.id.tv_appointment_serve_address)
    TextView tv_appointment_serve_address; // 服务地址
    @Bind(R.id.ll_comment)
    LinearLayout ll_comment; //买家留言LinearLayout
    @Bind(R.id.ed_appointment_leave_message)
    TextView ed_appointment_leave_message; // 买家留言
    @Bind(R.id.tv_service_order_count_money)
    TextView tv_service_order_count_money; //订单总价
    @Bind(R.id.tv_service_order_conpunt_money)
    TextView tv_service_order_conpunt_money; //优惠券价格
    @Bind(R.id.order_detail_tv_disbursements_money)
    TextView order_detail_tv_disbursements_money; //实付款
    @Bind(R.id.order_detail_tv_disbursements)
    TextView order_detail_tv_disbursements ; // 提示文字
    @Bind(R.id.order_detail_tv_payment_time)
    TextView order_detail_tv_payment_time; // 订单支付时间
    @Bind(R.id.order_detail_tv_payment_number)
    TextView order_detail_tv_payment_number; //订单编号
    @Bind(R.id.order_evaluation_start)
    StarLayout arlreadyEvaluation ; //已评价星级
    @Bind(R.id.rl_deal_close)
    RelativeLayout rl_deal_close; //评价完成
    @Bind(R.id.rl_deal_no_close)
    RelativeLayout rl_deal_no_close; //待评价
    @Bind(R.id.rl_serve_pass)
    RelativeLayout rl_serve_pass; // 服务密码
    @Bind(R.id.tv_serve_pass)
    TextView tv_serve_pass; //密码文本
    @Bind(R.id.appointment_detail_tv_reimburse)
    TextView appointment_detail_tv_reimburse; //申请退款按钮
    @Bind(R.id.appointment_detail_tv_check_logistics)
    TextView appointment_detail_tv_check_logistics; //预约详情头部栏中左边按钮
    @Bind(R.id.appointment_detail_tv_check_receipt)
    TextView appointment_detail_tv_check_receipt; //预约详情头部栏中右边按钮
    @Bind(R.id.appointment_ll_cosmetologist)
    LinearLayout llCosmetologist;//美容师信息
    @Bind(R.id.appointment_ll_store_info)
    RelativeLayout llStore_info; //商家信息
    @Bind(R.id.ll_service_time)
    LinearLayout ll_service_time ; //预约时间
    @Bind(R.id.training_detail_iv_tel)
    ImageView telImage; //电话标志
    @Bind(R.id.tv_appointemnt_goods_businessmen_information)
    TextView storeInfo; // 商家信息
    private ServiceOrderDetial serviceOrderDetial;
    private Activity mActivity;
    private String mStatus; // 状态
    private String orderId; //订单Id
    private String refundId; //退款id
    private String typeId, gcId,order_state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_appointment_detail);
        ButterKnife.bind(this);
        mActivity = AppointmentDetailActivity.this;
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        titleView.setTitle(R.string.appointment_detial_text);
        titleView.setLeftImageButton(R.mipmap.back);
        titleView.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initView() {
        mStatus = getIntent().getStringExtra("status");
        orderId = getIntent().getStringExtra("orderId");
        typeId = getIntent().getStringExtra("typeId");
        refundId = getIntent().getStringExtra("refundId");
        gcId = getIntent().getStringExtra("gcId");
        order_state = getIntent().getStringExtra("order_state");
        if ("1".equals(gcId)) {
            //1 服务类
            llCosmetologist.setVisibility(View.VISIBLE);
            llStore_info.setVisibility(View.GONE);
            ll_service_time.setVisibility(View.VISIBLE);
            ll_address_serve.setVisibility(View.VISIBLE);
//            rl_serve_pass.setVisibility(View.VISIBLE);
        } else { //其他几种类型
            llCosmetologist.setVisibility(View.GONE);
            llStore_info.setVisibility(View.VISIBLE);
            ll_address_serve.setVisibility(View.GONE);
            ll_service_time.setVisibility(View.GONE);
        }
        if (!AbStrUtil.isEmpty(mStatus)) {
            if ("退款/售后".equals(mStatus)) {
                appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
                appointment_refund_detali_rl.setVisibility(View.VISIBLE);
                appointment_refund_detali_rl.setOnClickListener(this);
            } else if ("待付款".equals(mStatus)) {
                appointment_detail_tv_order_state.setText("待付款");
                appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
                appointment_detail_tv_check_logistics.setText("取消订单");
                appointment_detail_tv_check_receipt.setText("马上支付");
                appointment_detail_tv_check_logistics.setVisibility(View.VISIBLE);
                appointment_detail_tv_check_receipt.setVisibility(View.VISIBLE);
                appointment_detail_tv_check_receipt.setOnClickListener(this);
            } else if ("待使用".equals(mStatus)) {
                appointment_detail_tv_order_state.setText("待使用");
                appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.order_status_color));
                rl_serve_pass.setVisibility(View.VISIBLE);
                appointment_detail_tv_reimburse.setOnClickListener(this);
                appointment_detail_tv_check_logistics.setVisibility(View.GONE);
                appointment_detail_tv_check_receipt.setVisibility(View.VISIBLE);
                appointment_detail_tv_check_receipt.setText("修改预约");
            } else if ("待评价".equals(mStatus)) {
                appointment_detail_tv_order_state.setText("待评价");
                appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.order_green_color));
                rl_deal_no_close.setVisibility(View.VISIBLE);
                rl_deal_no_close.setOnClickListener(this);
            } else if("交易完成".equals(mStatus)){
                appointment_detail_tv_order_state.setText("交易完成");
                appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.black_3));
            }
        }
        rl_technician_detail.setOnClickListener(this);
        appointment_detail_tv_check_receipt.setOnClickListener(this);
        appointment_detail_tv_check_logistics.setOnClickListener(this);

    }

    @Override
    protected void setData() {
        getHttpOrderService();
    }

    /**
     * 获取服务详情
     */
    private void getHttpOrderService() {
        HttpParams params = new HttpParams();
        String url = "";
        if ("退款/售后".equals(mStatus)) {
            params.put("refundId", refundId);
            url = Config.SERVICE_ORDER_REFUND_REFUNDD_ETIAL;
        } else {
            params.put("orderId", orderId);
            url = Config.SERVICE_ORDER_DETAIL;
        }
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                serviceOrderDetial = AbJsonUtil.fromJson(result.toString(), new TypeToken<ServiceOrderDetial>() {
                });
                if (serviceOrderDetial != null) {
                    initOrderServiceData();
                }
            }

            @Override
            public void onError(String code, String message) {
                /*Tool.showTextToast(context, message);
                finish();*/
                status.showNoData(message, "重新加载", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        status.showLoading();
                        getHttpOrderService();
                    }
                });
            }
        });
    }

    /**
     * 填充数据
     */
    private void initOrderServiceData() {
        if ("退款/售后".equals(mStatus)) {
            appointment_detail_tv_order_state.setText(order_state);
            appointment_detail_tv_order_state.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
        }
        if ("0".equals(serviceOrderDetial.getIsMainStore())) {
            appointment_detail_tv_order_name.setText("加盟店");
        } else {
            appointment_detail_tv_order_name.setText("总店商品");
        }
        GlideHelper.showImage(this, serviceOrderDetial.getGoodsImage(), all_order_item_iv);
        GlideHelper.showImage(this, serviceOrderDetial.getPhotoImage(), iv_portrait);
        all_order_item_tv_detail.setText(serviceOrderDetial.getGoodsName());
        all_order_item_tv_price.setText("￥" + serviceOrderDetial.getGoodsPrice());
        all_order_item_tv_amount.setText("x" + serviceOrderDetial.getGoodsNum());
        tv_technician_name.setText(serviceOrderDetial.getName());
        tv_appointment_serve_time.setText(serviceOrderDetial.getServiceTime());
        tv_appointment_serve_address.setText(serviceOrderDetial.getAddress());
        storeInfo.setText(serviceOrderDetial.getAddress());
        ed_appointment_leave_message.setText(serviceOrderDetial.getRemark());
        if (serviceOrderDetial.getServicePwd() != null && serviceOrderDetial.getServicePwd().size() != 0) {
            tv_serve_pass.setText(serviceOrderDetial.getServicePwd().get(0));
        }
        if("交易完成".equals(mStatus)){
            showDefalutView();
        }
        if("0".equals(serviceOrderDetial.getPaymentState())){
            order_detail_tv_disbursements.setText("待付款:");
        }else if("1".equals(serviceOrderDetial.getPaymentState())){
            order_detail_tv_disbursements.setText("已付款:");
        }
        storeInfo.setText(serviceOrderDetial.getStoreName());
        tv_service_order_count_money.setText(serviceOrderDetial.getOrderTotalPrice());
        tv_service_order_conpunt_money.setText(serviceOrderDetial.getCouponPrice());
        order_detail_tv_disbursements_money.setText(serviceOrderDetial.getOrderAmount());
        if("待付款".equals(mStatus)){
            order_detail_tv_payment_time.setText("下单时间:" + serviceOrderDetial.getCreateTime());
        }else{
            order_detail_tv_payment_time.setText("付款时间:" + serviceOrderDetial.getPaymentTime());
        }
        order_detail_tv_payment_number.setText("订单编号:" + serviceOrderDetial.getOrderSn());
        rl_goods_info_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null ;
                if("1".equals(gcId)){
                    intent = new Intent(context, ServiceDetailActivity.class);
                }else if("5".equals(gcId)){
                    intent = new Intent(context, CosmeticTrainingDetailActivity.class);
                }else{
                    intent = new Intent(context, BeautyClinicDetailActivity.class);
                    intent.putExtra("type",gcId);
                }
                intent.putExtra("goodsId", serviceOrderDetial.getGoodsId());
                startActivity(intent);
            }
        });
        telImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!AbStrUtil.isEmpty(serviceOrderDetial.getStoreTel())) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + serviceOrderDetial.getStoreTel()));
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivity(intent);
                    }
                } else {
                    Tool.showTextToast(context, "暂无商家电话");
                }
            }
        });
    }

    /**
     * 展示不同的评价视图
     */
    private void showDefalutView(){
        if("1".equals(serviceOrderDetial.getEvaluationStatus())){ //已评价
            rl_deal_close.setVisibility(View.VISIBLE);
            rl_deal_no_close.setVisibility(View.GONE);
            arlreadyEvaluation.setStarNumber(serviceOrderDetial.getGrade());
        } else if("0".equals(serviceOrderDetial.getEvaluationStatus())){ //未评价
            rl_deal_close.setVisibility(View.GONE);
            rl_deal_no_close.setVisibility(View.VISIBLE);
            rl_deal_no_close.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        if(serviceOrderDetial == null){
            return ;
        }
        final String orderId = serviceOrderDetial.getOrderId(); //订单Id
        switch (v.getId()) {
            case R.id.appointment_detail_tv_reimburse: //申请退款按钮
                intent.setClass(context, AppointmentSaleActivity.class);
                intent.putExtra("orderName", serviceOrderDetial.getGoodsName());
                intent.putExtra("typeId", serviceOrderDetial.getTypeId());
                intent.putExtra("orderId", orderId);
                startActivity(intent);
                AppointmentDetailActivity.this.finish();
                break;

            case R.id.rl_deal_no_close://待评论
                intent.setClass(context, AppointmentEvaluationActivity.class);
                intent.putExtra("o2oService.o2oServiceOrderId", orderId);
                intent.putExtra("typeId", serviceOrderDetial.getTypeId());
                intent.putExtra("gcId", serviceOrderDetial.getGcId());
                intent.putExtra("orderName", serviceOrderDetial.getGoodsName());
                intent.putExtra("beautician.businessId", serviceOrderDetial.getBeauticianId());
                intent.putExtra("businessImage",serviceOrderDetial.getPhotoImage());
                intent.putExtra("goodimage",serviceOrderDetial.getGoodsImage());
                intent.putExtra("businessName",serviceOrderDetial.getName());
                intent.putExtra("beautician.o2oServiceOrderId",serviceOrderDetial.getGoodsId());
                startActivity(intent);
                AppointmentDetailActivity.this.finish();
                break;

            case R.id.rl_technician_detail: //美容师
                intent.setClass(context, CosmetologistActivity.class);
                intent.putExtra("beauticianId", serviceOrderDetial.getBeauticianId());
                startActivity(intent);
                break;

            case R.id.appointment_detail_tv_check_receipt: //马上支付
                if (appointment_detail_tv_check_receipt.getText().toString().equals("马上支付")) {
                    intent.setClass(context, CashierDeskActivity.class);
                    String type = "";
                    if ("1".equals(serviceOrderDetial.getTypeId())) {
                        //美服务
                        type = GlobalType.SERVICE_TYPE;
                        intent.putExtra(CashierDeskActivity.ORDER_TYPE, "FW"); // 订单类型
                    } else if ("2".equals(serviceOrderDetial.getTypeId())) {
                        //2美容培训
                        type = GlobalType.TRAIN_TYPE;
                        intent.putExtra(CashierDeskActivity.ORDER_TYPE, "PX"); // 订单类型
                    }
                    OrderResult mOrderResult = new OrderResult(serviceOrderDetial.getOrderAmount(), orderId, type);
                    intent.putExtra(CashierDeskActivity.ORDER_RESULT, mOrderResult);
                    intent.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY);
                    HashMap<String, Class> map = new HashMap<>();
                    map.put(CashierDeskActivity.GOTO_ACTIVITY, MyAllAppointmentActivity.class);
                    intent.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
                    startActivity(intent);
                } else if (appointment_detail_tv_check_receipt.getText().toString().equals("修改预约")) {
                    if ("1".equals(serviceOrderDetial.getTypeId())) {
                        //美服务
                        Bundle bundle = new Bundle();
                        bundle.putString("type",GlobalType.CHANGE_RESERVATION);
                        bundle.putString("goodsId", serviceOrderDetial.getGoodsId());
                        bundle.putString("price", serviceOrderDetial.getGoodsPrice());
                        bundle.putString("isMainStore", serviceOrderDetial.getIsMainStore());
                        bundle.putString("goodsBody", serviceOrderDetial.getGoodsName());
                        bundle.putString("goodsImage", serviceOrderDetial.getGoodsImage());
                        bundle.putString("beauticianId", serviceOrderDetial.getBeauticianId());
                        bundle.putString("orderId", serviceOrderDetial.getOrderId());
                        startActivityForResult(bundle,1,ReservationActivity.class);
                    } else if ("2".equals(serviceOrderDetial.getTypeId())) {
                        //2美容培训
                        AbToastUtil.showToast(context,"培训类订单不可修改");
                    }
                }
                break;
            case R.id.appointment_detail_tv_check_logistics: //取消订单
                new AlertDialogFragment.Builder()
                        .setContentText("确认取消订单")
                        .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                    @Override
                    public void dialogLeftBtnClick() {
                        cancelOrder(orderId);

                    }
                }).setRightBtnText("取消")
                        .build()
                        .show(getSupportFragmentManager(), AlertDialogFragment.TAG);
                break;

            case R.id.appointment_refund_detali_rl: //查看退款详情
                intent.putExtra("refundId",serviceOrderDetial.getRefundId());
                intent.setClass(context,OrderRefundActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_goods_info_layout:
                intent.setClass(mActivity,ServiceDetailActivity.class);
                intent.putExtra("goodsId",serviceOrderDetial.getOrderId());
                startActivity(intent);
                break;

//            case R.id.tv_appointment_item_contact_service: //联系客服
//                if(serviceOrderDetial.getIsMainStore().equals("1")){
//                    Tool.SelectCustomerService(context,true);
//                }else{
//                    Tool.SelectCustomerService(context,false);
//                }
//
        }
    }

    /**
     * 取消预约订单
     */
    private void cancelOrder(String orderId) {
        HttpParams params = new HttpParams();
        params.put("orderId", orderId);
        HttpUtils.post(Config.SERVICE_ORDER_CANCEL, params, new HttpCallBack(this, "数据请求中") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context, message);
                notifyOrderList();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }

    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.APPOINTMENT_DETIAL);
        sendBroadcast(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //需要刷新当页数据 调用startActivityForResult(bundle,1,ReservationActivity.class);
         // 设置setResult(RESULT_OK);
        if (resultCode==RESULT_OK&&requestCode==1){
            getHttpOrderService();
        }
    }
}
